﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Morus;
using KAKA.Infrastructure;
using System.Collections.ObjectModel;

namespace KAKA.Domain
{
    public partial class User : IAggregateRoot
    {
        public static User Create(string email, string password, string gender, string nickname)
        {
            var user = new User();
            var crypto = IoC.Resolve<Cryptography>();
            var salt = crypto.GenerateSalt();
            var pwd = crypto.GeneratePassword(password, salt);

            user.HashSalt = Convert.ToBase64String(salt);
            user.Password = Convert.ToBase64String(pwd);
            user.Username = email;
            user.Email = email;
            user.Lockout = false;
            user.Role = Role.User;
            user.LastActAt = DateTime.Now;
            user.CreateAt = DateTime.Now;
            user.Id = Guid.NewGuid();

            var member = Member.Create(user);

            member.Grade = Grade.Member;
            member.Nickname = nickname;
            member.Gender = gender.ToEnum<Gender>(Gender.None);

            return user;
        }

        public bool Verify(string username, string password)
        {
            Check.Argument.IsNotEmpty(username, "username");
            Check.Argument.IsNotEmpty(password, "password");

            var salt = Convert.FromBase64String(HashSalt);
            var pwd = IoC.Resolve<Cryptography>().GeneratePassword(password, salt);

            if (Username.ToLower() == username.ToLower() && Password == Convert.ToBase64String(pwd))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public Proof LatestProof
        {
            get
            {
                return this.Proofs.OrderByDescending(r => r.CreateAt).FirstOrDefault(r => r.Mobile != null);
            }
        }
    }
}
